﻿using GzucmAspBigJob.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace GzucmAspBigJob.Utils
{
    public class ValidChecker
    {
        /// <summary>
        /// 使用如下
        /// var result =ValidatetionHelper.IsValid(obj);
        /// if (!result.IsVaild){ 如果非法 打印结果即可
        ///     foreach (ErrorMember errorMember in result.ErrorMembers){
        ///         Console.WriteLine(errorMember.ErrorMemberName+"："+errorMember.ErrorMessage);
        ///     }
        /// }
        /// 检查传递的字段是否符合在Model处填写的限制
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static ValidResult IsValid(object obj)
        {
            ValidResult result = new ValidResult();
            try
            {
                var validationContext = new ValidationContext(obj);
                var results = new List<ValidationResult>();
                var isValid = Validator.TryValidateObject(obj, validationContext, results, true);

                if (!isValid)
                {
                    result.IsVaild = false;
                    result.ErrorMemberList = new List<ErrorMember>();
                    foreach (var item in results)
                    {
                        result.ErrorMemberList.Add(new ErrorMember()
                        {
                            ErrorMessage = item.ErrorMessage,
                            ErrorMemberName = item.MemberNames.FirstOrDefault()
                        });
                    }
                }
                else
                {
                    result.IsVaild = true;
                }
            }
            catch (Exception ex)
            {
                result.IsVaild = false;
                result.ErrorMemberList = new List<ErrorMember>();
                result.ErrorMemberList.Add(new ErrorMember()
                {
                    ErrorMessage = ex.Message,
                    ErrorMemberName = "Internal Excepetion"
                });
            }
            return result;
        }
    }
}